import React from 'react';
import {
    Drawer,
    Box,
    Typography,
    List,
    ListItem,
    ListItemIcon,
    ListItemText,
    Divider,
    IconButton,
    Collapse,
    ListItemButton, // 导入 ListItemButton
} from '@mui/material';
import {
    ErrorOutline as ErrorIcon,
    WarningAmber as WarningIcon,
    ExpandLess,
    ExpandMore,
    Close as CloseIcon,
} from '@mui/icons-material';
import { useFlowStore } from '../store/flowStore';
import { useReactFlow } from '@xyflow/react';
import type { ValidationError } from '../utils/validator';
import { LAYOUT_CONSTANTS } from '../constants/layout';

/**
 * @interface ProblemsPanelProps
 * @description 定义问题面板组件的 props 接口。
 */
interface ProblemsPanelProps {
    open: boolean;
    onClose: () => void;
}

/**
 * @function ProblemsPanel
 * @description 问题面板组件，用于展示行为树的验证错误和警告。
 * 用户可以点击错误项，画布将自动定位到对应的节点。
 */
const ProblemsPanel: React.FC<ProblemsPanelProps> = ({ open, onClose }) => {
    // 从 Zustand store 获取错误状态和节点数据
    const { errors, nodes } = useFlowStore();
    // 获取 React Flow 实例的 setCenter 方法
    const { setCenter } = useReactFlow();

    // 内部状态，用于控制错误和警告列表的展开/折叠
    const [openErrors, setOpenErrors] = React.useState(true);
    const [openWarnings, setOpenWarnings] = React.useState(true);

    const handleToggleErrors = () => {
        setOpenErrors(!openErrors);
    };

    const handleToggleWarnings = () => {
        setOpenWarnings(!openWarnings);
    };

    /**
     * @function handleItemClick
     * @description 处理错误或警告项的点击事件。
     * 当点击一个错误或警告时，画布会平移并缩放以将相关的节点定位到视图中心。
     * @param {string} nodeId - 错误或警告关联的节点 ID。
     */
    const handleItemClick = (nodeId: string) => {
        const node = nodes.find((n) => n.id === nodeId);
        if (!node) {
            console.warn(`Node with id ${nodeId} not found`);
            return;
        }
        
        // 使用默认尺寸或从节点属性获取实际尺寸
        const nodeWidth = node.width ?? LAYOUT_CONSTANTS.NODE_WIDTH; // 使用默认值
        const nodeHeight = node.height ?? LAYOUT_CONSTANTS.NODE_HEIGHT;
        
        // 使用 setCenter 定位到节点中心
        setCenter(
            node.position.x + nodeWidth / 2,
            node.position.y + nodeHeight / 2,
            { zoom: 1.5, duration: 500 }
        );
        onClose(); // 点击后关闭面板
    };

    // 过滤出错误和警告
    const actualErrors = errors.filter(err => err.type === 'error');
    const actualWarnings = errors.filter(err => err.type === 'warning');

    return (
        <Drawer
            anchor="bottom"
            open={open}
            onClose={onClose}
            variant="temporary"
            sx={{
                '& .MuiDrawer-paper': {
                    height: '30%', // 面板高度
                    maxHeight: '400px', // 最大高度
                    overflow: 'hidden', // 隐藏溢出内容
                },
                zIndex: (theme) => theme.zIndex.drawer + 2, // 确保在其他抽屉之上
            }}
        >
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', p: 1.5, borderBottom: '1px solid rgba(255, 255, 255, 0.12)' }}>
                <Typography variant="h6">问题</Typography>
                <IconButton onClick={onClose} size="small">
                    <CloseIcon />
                </IconButton>
            </Box>
            <Box sx={{ flexGrow: 1, overflowY: 'auto' }}>
                <ListItemButton onClick={handleToggleErrors}>
                    <ListItemIcon>
                        <ErrorIcon color="error" />
                    </ListItemIcon>
                    <ListItemText primary={`错误 (${actualErrors.length})`} />
                    {openErrors ? <ExpandLess /> : <ExpandMore />}
                </ListItemButton>
                <Collapse in={openErrors} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding dense>
                        {actualErrors.length === 0 ? (
                            <ListItem sx={{ pl: 4 }}>
                                <ListItemText secondary="无错误" />
                            </ListItem>
                        ) : (
                            actualErrors.map((error: ValidationError, index: number) => (
                                <ListItemButton key={index} sx={{ pl: 4 }} onClick={() => handleItemClick(error.nodeId!)}>
                                    <ListItemIcon>
                                        <ErrorIcon fontSize="small" color="error" />
                                    </ListItemIcon>
                                    <ListItemText primary={error.message} secondary={`节点ID: ${error.nodeId}`} />
                                </ListItemButton>
                            ))
                        )}
                    </List>
                </Collapse>

                <Divider />

                <ListItemButton onClick={handleToggleWarnings}>
                    <ListItemIcon>
                        <WarningIcon color="warning" />
                    </ListItemIcon>
                    <ListItemText primary={`警告 (${actualWarnings.length})`} />
                    {openWarnings ? <ExpandLess /> : <ExpandMore />}
                </ListItemButton>
                <Collapse in={openWarnings} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding dense>
                        {actualWarnings.length === 0 ? (
                            <ListItem sx={{ pl: 4 }}>
                                <ListItemText secondary="无警告" />
                            </ListItem>
                        ) : (
                            actualWarnings.map((warning: ValidationError, index: number) => (
                                <ListItemButton key={index} sx={{ pl: 4 }} onClick={() => handleItemClick(warning.nodeId!)}>
                                    <ListItemIcon>
                                        <WarningIcon fontSize="small" color="warning" />
                                    </ListItemIcon>
                                    <ListItemText primary={warning.message} secondary={`节点ID: ${warning.nodeId}`} />
                                </ListItemButton>
                            ))
                        )}
                    </List>
                </Collapse>
            </Box>
        </Drawer>
    );
};

export default ProblemsPanel;